package com.cu.employmentmanagementsystem.common.aop;

import cn.dev33.satoken.stp.StpUtil;
import com.cu.employmentmanagementsystem.entity.User;
import com.cu.employmentmanagementsystem.common.exception.ServiceException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CurrentAccountAspect
{

    @Pointcut("@annotation(com.cu.employmentmanagementsystem.common.annotation.InjectCurrentAccount)")
    public void injectCurrentAccountPointcut()
    {
        // 获取注解信息并进行处理
    }


    @Around("injectCurrentAccountPointcut()")
    public Object setCurrentAccount(ProceedingJoinPoint joinPoint)
    {
        try
        {
            String account;
            try
            {
                account = StpUtil.getLoginIdAsString();
            }
            catch (Exception e)
            {
                return joinPoint.proceed();
            }

            Object[] args = joinPoint.getArgs();

            if (args == null || args.length == 0)
            {
                return joinPoint.proceed();
            }

            for (int i = 0; i < args.length; i++)
            {
                Object arg = args[i];
                if (arg == null)
                {
                    args[i] = account;
                    continue;
                }

                Class<?> argClass = arg.getClass();
                if (argClass == User.class)
                {
                    User user = (User) arg;
                    user.setAccount(account);
                }
            }

            return joinPoint.proceed(args);
        }
        catch (Throwable e)
        {
            throw new ServiceException("注入当前用户失败");
        }
    }
}